<?php
namespace app\index\controller;
use think\Session;
use think\Controller;
use think\Db;
class Branch extends Controller
{
    public function Add()
    {
        if (session("login")!=1) return $this->error("请先登录");
        if (session("cid")!=0) return $this->error("无权访问");
        if (isset($_POST["add"])) {
            $result=db('clinic')->insertGetId(["name"=>$_POST["name"],"address"=>$_POST["address"],"tel"=>$_POST["tel"]]);
            if ($result!=null) {
                $res=db('admin')->insert(["user"=>$_POST["admin"],"passwd"=>md5($_POST["pass"]),"clinic"=>$result]);
                if ($res==1) $this->success('新增成功','/Branch/List');
                else $this->error('新增失败');
            } else {
                $this->error('新增失败');
            }
        }else {
            return view('add');
        }   
    }
    public function Edit()
    {
        if (session("login")!=1) return $this->error("请先登录");
        if (session("cid")!=0) return $this->error("无权访问");
        $aid=input('id');
        $result=Db::query("SELECT * FROM clinic,admin WHERE (clinic.id = admin.clinic) and (admin.id={$aid})");
        if (isset($_POST["edit"])) {
            if($_POST['pass']!=$result[0]["passwd"]) $_POST["pass"]=md5($_POST["pass"]);
            $cid=db("admin")->field("clinic")->where("id",$aid)->find();
            $resa=db("clinic")->where("id",$cid["clinic"])->update(["name"=>$_POST["name"],"address"=>$_POST["address"],"tel"=>$_POST["tel"]]);
            $resb=db("admin")->where("id",$aid)->update(["user"=>$_POST["admin"],"passwd"=>$_POST["pass"]]);
            if (($resa==1) || ($resb==1)) {
                $this->success('更新成功','/Branch/List');
            } else {
                $this->error('更新失败');
            }
        }else{
            return view('edit',$result[0]);
        }
    }
    public function List(){
        if (session("login")!=1) return $this->error("请先登录");
        if (session("cid")!=0) return $this->error("无权访问");
        $result=Db::query("SELECT * FROM clinic,admin WHERE clinic.id = admin.clinic");
        $this->assign("arr",$result);
        return $this->fetch('list');
    }
    public function Del(){
        if (session("login")!=1) return $this->error("请先登录");
        if (session("cid")!=0) return $this->error("无权访问");
        $aid=input('id');
        if($aid==0) return $this->error('总店不允许删除');
        $cid=db("admin")->field("clinic")->where("id",$aid)->find()["clinic"];
        $resa=db('admin')->delete($aid);
        $resc=db('clinic')->delete($cid);
        if (($resa==1) && ($resc==1)) {
            $this->success('删除成功','/Branch/List');
        } else {
            $this->error('删除失败');
        }
    }
}